package com.yklx.youke.controller;

import com.yklx.youke.admin.service.ScheduleService;
import com.yklx.youke.entity.Schedule;
import com.yklx.youke.entity.Session;
import com.yklx.youke.service.SessionService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/admin")
@CrossOrigin(origins = "*")
public class ScheduleController {

    private final ScheduleService scheduleService;
    private final SessionService sessionService;

    public ScheduleController(ScheduleService scheduleService, SessionService sessionService) {
        this.scheduleService = scheduleService;
        this.sessionService = sessionService;
    }

    @GetMapping("/schedules")
    public ResponseEntity<List<Schedule>> getAllSchedules() {
        try {
            List<Session> sessions = sessionService.getAllSessions();
            List<Schedule> schedules = convertSessionsToSchedules(sessions);
            
            return ResponseEntity.ok(schedules);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().build();
        }
    }

    @GetMapping("/teacher/schedules")
    public ResponseEntity<List<Schedule>> getTeacherSchedules(@RequestParam String teacherId) {
        try {
            List<Session> allSessions = sessionService.getAllSessions();
            // 过滤出指定教师的会话，添加空值检查
            List<Session> teacherSessions = allSessions.stream()
                .filter(session -> session.getTeacher() != null && 
                        session.getTeacher().getUserId() != null && 
                        session.getTeacher().getUserId().toString().equals(teacherId))
                .collect(Collectors.toList());
                
            List<Schedule> schedules = convertSessionsToSchedules(teacherSessions);
            
            return ResponseEntity.ok(schedules);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().build();
        }
    }

    @GetMapping("/schedules/{scheduleId}")
    public ResponseEntity<Schedule> getScheduleById(@PathVariable String scheduleId) {
        try {
            UUID sessionId = UUID.fromString(scheduleId);
            Session session = sessionService.getSessionById(sessionId);
            
            if (session != null) {
                Schedule schedule = convertSessionToSchedule(session);
                return ResponseEntity.ok(schedule);
            } else {
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().build();
        }
    }

    @PostMapping("/schedules")
    public ResponseEntity<Map<String, Object>> createSchedule(@RequestBody Schedule schedule) {
        try {
            Session session = convertScheduleToSession(schedule);
            boolean success = sessionService.createSession(session);
            if (success) {
                return ResponseEntity.ok(Map.of("message", "Schedule created successfully", "success", true));
            } else {
                return ResponseEntity.badRequest().body(Map.of("message", "Failed to create schedule", "success", false));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().body(Map.of("message", "Error creating schedule: " + e.getMessage(), "success", false));
        }
    }

    @PutMapping("/schedules/{scheduleId}")
    public ResponseEntity<Map<String, Object>> updateSchedule(@PathVariable String scheduleId, @RequestBody Schedule schedule) {
        try {
            // 从路径变量获取sessionId
            UUID sessionId = UUID.fromString(scheduleId);
            
            Session session = sessionService.getSessionById(sessionId);
            if (session == null) {
                return ResponseEntity.notFound().build();
            }
            
            // 更新session信息
            session.setSubject(schedule.getCourseId());
            session.setScheduledTime(schedule.getStartTime());
            session.setDuration((int)(java.time.Duration.between(schedule.getStartTime(), schedule.getEndTime()).toMinutes()));
            session.setStatus(Session.SessionStatus.valueOf(schedule.getStatus()));
            
            boolean success = sessionService.updateSession(session);
            if (success) {
                return ResponseEntity.ok(Map.of("message", "Schedule updated successfully", "success", true));
            } else {
                return ResponseEntity.badRequest().body(Map.of("message", "Failed to update schedule", "success", false));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().body(Map.of("message", "Error updating schedule: " + e.getMessage(), "success", false));
        }
    }

    @DeleteMapping("/schedules/{scheduleId}")
    public ResponseEntity<Map<String, Object>> deleteSchedule(@PathVariable String scheduleId) {
        try {
            UUID sessionId = UUID.fromString(scheduleId);
            boolean success = sessionService.deleteSession(sessionId);
            if (success) {
                return ResponseEntity.ok(Map.of("message", "Schedule deleted successfully", "success", true));
            } else {
                return ResponseEntity.badRequest().body(Map.of("message", "Failed to delete schedule", "success", false));
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.badRequest().body(Map.of("message", "Error deleting schedule: " + e.getMessage(), "success", false));
        }
    }
    
    // 将多个Session转换为Schedule列表的辅助方法
    private List<Schedule> convertSessionsToSchedules(List<Session> sessions) {
        List<Schedule> schedules = new ArrayList<>();
        for (Session session : sessions) {
            try {
                schedules.add(convertSessionToSchedule(session));
            } catch (Exception e) {
                e.printStackTrace();
                // 跳过有问题的session，继续处理其他session
                continue;
            }
        }
        return schedules;
    }
    
    // 从Session转换为Schedule的辅助方法
    private Schedule convertSessionToSchedule(Session session) {
        Schedule schedule = new Schedule();
        schedule.setScheduleId(session.getSessionId().toString());
        // 这里使用占位符，因为Session实体中没有courseId字段
        schedule.setCourseId(session.getSubject());
        // 添加空值检查，防止NullPointerException
        if (session.getTeacher() != null && session.getTeacher().getUserId() != null) {
            schedule.setTeacherId(session.getTeacher().getUserId().toString());
        } else {
            schedule.setTeacherId("unknown"); // 或者其他默认值
        }
        schedule.setStartTime(session.getScheduledTime());
        // 设置结束时间（根据持续时间计算）
        int duration = session.getDuration() != null ? session.getDuration() : 60; // 默认60分钟
        schedule.setEndTime(session.getScheduledTime().plusMinutes(duration));
        schedule.setStatus(session.getStatus().name());
        schedule.setMaxParticipants(1); // Session默认是1对1的，所以设为1
        schedule.setCreatedAt(session.getCreatedAt());
        schedule.setUpdatedAt(session.getUpdatedAt());
        
        return schedule;
    }
    
    // 从Schedule转换为Session的辅助方法
    private Session convertScheduleToSession(Schedule schedule) {
        Session session = new Session();
        if (schedule.getScheduleId() != null && !schedule.getScheduleId().isEmpty()) {
            session.setSessionId(UUID.fromString(schedule.getScheduleId()));
        }
        // 注意：这里需要关联实际的Teacher和Student对象，这需要额外的查询
        // 由于Session关联的是Teacher和Student实体，而不是简单的ID，这里简化处理
        session.setSubject(schedule.getCourseId());
        session.setScheduledTime(schedule.getStartTime());
        session.setDuration((int)(java.time.Duration.between(schedule.getStartTime(), schedule.getEndTime()).toMinutes()));
        session.setStatus(Session.SessionStatus.valueOf(schedule.getStatus()));
        
        return session;
    }
}